<template>
  <v-card flat height="660" class="pa-5">
    <v-row class="align-center pl-3" no-gutters>
      <v-col cols="4">
        <v-text-field
          v-model="search"
          class="white-input align-center"
          append-outer-icon="mdi-magnify"
          placeholder="Keyword Search"
          solo
          dense
          hide-details
        ></v-text-field
      ></v-col>
      <v-col class="d-flex align-center checkbox pl-10" cols="3">
        <v-checkbox
          v-model="propItemsInfo.type"
          value="In Use"
          label="In Use"
          class="ma-0 mr-2"
          hide-details
        ></v-checkbox>
        <v-checkbox
          v-model="propItemsInfo.type"
          label="Disposed"
          value="Disposed"
          hide-details
          class="ma-0"
        ></v-checkbox>
      </v-col>
    </v-row>
    <v-row class="pl-3 mb-2 mt-3" no-gutters>
      <v-col cols="6">
        <v-select
          :items="addressList"
          v-model="propItemsInfo.address"
          :item-value="addressItemText"
          :item-text="addressItemText"
          placeholder="Place select address"
          class="white-input"
          solo
          dense
          hide-details
        >
          <template #item="{ item }">
            {{ item.locationCode }}{{ item.parentLocation }} {{ item.address }}
          </template>
        </v-select>
      </v-col>
    </v-row>
    <v-data-table
      :headers="headers"
      :items="propItemsInfo.items"
      :search="search"
      item-key="item"
      show-select
      class="elevation-0 form-info"
      hide-default-footer
    >
      <template #[`header.data-table-select`]>
        <v-btn
          @click="openAddItem"
          class="rounded-pill"
          elevation="0"
          color="#79839B"
          width="20px"
          height="20px"
          fab
        >
          <v-icon color="#fff" size="16"> mdi-plus-thick </v-icon>
        </v-btn>
      </template>
      <template #[`item.data-table-select`]> </template>
      <template #[`item.action`]="{ item }">
        <div class="action d-flex">
          <v-img
            v-if="item.attachment.productPhoto"
            class="flex-grow-0 rounded-sm mr-1"
            :src="item.attachment.productPhoto"
            height="33.33px"
            width="33.33px"
          ></v-img>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-btn
                @click="openAttachment(item)"
                v-on="on"
                class="pa-0"
                icon
                depressed
              >
                <v-icon size="18" color="#79839B">mdi-folder</v-icon>
              </v-btn>
            </template>
            Attachment
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-btn
                @click="openDisposeDetails"
                v-on="on"
                class="pa-0"
                icon
                depressed
              >
                <v-icon size="18" color="#79839B">mdi-close-box</v-icon>
              </v-btn>
            </template>
            Dispose Details
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-btn
                @click="openEditItem(item)"
                v-on="on"
                class="pa-0"
                icon
                depressed
              >
                <v-icon size="18" color="#79839B">
                  mdi-square-edit-outline
                </v-icon>
              </v-btn>
            </template>
            Edit Item
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-btn
                @click="openDelete(item)"
                v-on="on"
                class="pa-0 rounded-pill"
                icon
                depressed
              >
                <v-icon size="18" color="#79839B"> mdi-delete </v-icon>
              </v-btn>
            </template>
            Delete Item
          </v-tooltip>
        </div>
      </template>
    </v-data-table>
    <Dialog v-model="showDialog" :title="dialogTitle" :width="dialogWidth">
      <template #headerAppend>
        <v-icon
          v-if="step === 4"
          @click="downloadAttachment"
          color="#fff"
          size="18"
          class="mr-4"
        >
          mdi-file-download
        </v-icon>
        <v-icon
          v-if="step === 4"
          @click="deleteAttachment"
          color="#fff"
          size="18"
          class="mr-4"
        >
          mdi-delete
        </v-icon>
        <v-icon
          v-if="![3, 4].includes(step)"
          @click="save"
          color="#fff"
          size="18"
          class="mr-4"
        >
          mdi-content-save
        </v-icon>
        <v-icon color="#fff" size="18" @click="closeDialog">mdi-close</v-icon>
      </template>
      <template>
        <AddItem v-if="step === 1" :selected.sync="addSelectedItem"></AddItem>
        <EditItem v-else-if="step === 2" ref="editItem"></EditItem>
        <Delete
          v-else-if="step === 3"
          @delete="save"
          title="Are you sure to delete this item?"
        ></Delete>
        <Attachment
          v-else-if="step === 4"
          :item="selectedItem"
          ref="attachment"
          @close="showDialog = false"
        ></Attachment>
        <DisposeDetails
          v-else-if="step === 5"
          ref="disposeDetails"
        ></DisposeDetails>
      </template>
    </Dialog>
  </v-card>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import {
  IAddress,
  IItems,
  IServiceContractItem,
  IItemsItem,
} from "@/components/Customer/index";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import AddItem from "@/components/Customer/Dialog/AddItem/AddItem.vue";
import EditItem from "@/components/Customer/Dialog/EditItem/EditItem.vue";
import Delete from "@/components/Customer/Dialog/Delete/Delete.vue";
import Attachment from "@/components/Customer/Dialog/Attachment/Attachment.vue";
import DisposeDetails from "@/components/Customer/Dialog/DisposeDetails/DisposeDetails.vue";
import { isValidKey } from "@/common/constants/Utils";
@Component({
  components: {
    Dialog,
    AddItem,
    EditItem,
    Delete,
    Attachment,
    DisposeDetails,
  },
  props: {
    itemsInfo: {
      type: Object,
      default: () => ({}),
    },
  },
})
export default class Items extends Vue {
  get propItemsInfo(): IItems {
    return this.$props.itemsInfo;
  }
  // 1.AddItem 2.EditItem 3.DeleteItem 4.Attachment 5.DisposeDetails
  step = -1;
  // Dialog
  dialogTitle = "";
  showDialog = false;
  get dialogWidth() {
    if ([3, 5].includes(this.step)) {
      return "480";
    } else if (this.step === 2) {
      return "548";
    } else {
      return "1152";
    }
  }
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    if (this.step === 4) {
      (this.$refs.attachment as Attachment).close();
    } else {
      this.showDialog = false;
    }
  }
  // address
  addressItemText(item: IAddress) {
    return `${item.locationCode}${item.parentLocation} ${item.address}`;
  }
  get addressList() {
    const addressTree = this.$store.state.ContactInfoStore.address;
    return this.flatAllAddress(addressTree);
  }
  flatAllAddress(addressList: IAddress[]) {
    var flatArr: IAddress[] = [];
    if (addressList.length) {
      addressList.forEach((address) => {
        flatArr.push(address);
        if (address.children) {
          flatArr.push(...this.flatAllAddress(address.children));
        }
      });
    }
    return flatArr;
  }
  // Table
  search = "";
  headers = [
    { text: "Item #", value: "itemNumber" },
    { text: "Item Description", value: "itemDescription" },
    { text: "Serial number", value: "serialNumber" },
    { text: "Alias", value: "alias" },
    { text: "Location code", value: "locationCode" },
    { text: "QTY", value: "QTY" },
    { text: "Cost", value: "cost" },
    { text: "Date Expire", value: "dateExpire" },
    { value: "action" },
  ];
  // action
  addSelectedItem: IItemsItem[] & IServiceContractItem[] = [];
  selectedItem: IServiceContractItem | null = null;
  openAddItem() {
    this.dialogTitle = "Add Item";
    this.step = 1;
    this.addSelectedItem = this.propItemsInfo.items;
    this.openDialog();
  }
  openEditItem(item: IServiceContractItem) {
    console.log(item);
    this.dialogTitle = "Edit Item";
    this.step = 2;
    this.selectedItem = item;
    this.$nextTick(() => {
      const editItemRef = this.$refs.editItem as EditItem;
      editItemRef.resetForm();
      setTimeout(() => {
        editItemRef.setFormData(item);
      });
    });
    this.openDialog();
  }
  editItem(item: IItems) {
    if (this.selectedItem) {
      Object.assign(this.selectedItem, item);
    }
  }
  openDelete(item: IServiceContractItem) {
    this.dialogTitle = "Delete";
    this.step = 3;
    this.selectedItem = item;
    this.openDialog();
  }
  deleteItem(itemId: string) {
    if (this.propItemsInfo && this.propItemsInfo.items.length) {
      const index = this.propItemsInfo.items.findIndex(
        (item) => item.id === itemId
      );
      if (index >= 0) {
        this.propItemsInfo.items.splice(index, 1);
      }
    }
  }
  openAttachment(item: IServiceContractItem) {
    this.dialogTitle = "";
    this.step = 4;
    this.selectedItem = item;
    this.openDialog();
  }
  deleteAttachment() {
    (this.$refs.attachment as Attachment).deleteFile();
  }
  downloadAttachment() {
    (this.$refs.attachment as Attachment).downloadFile();
  }
  openDisposeDetails() {
    this.dialogTitle = "Dispose Details";
    this.step = 5;
    this.$nextTick(() => {
      (this.$refs.disposeDetails as DisposeDetails).resetForm();
    });
    this.openDialog();
  }

  async save() {
    if (this.step === 1) {
      this.propItemsInfo.items = this.addSelectedItem.map((item) => {
        if (!isValidKey("attachments", item)) {
          item.attachment = {
            productPhoto: "",
            attachmentList: [],
          };
        }
        return item;
      }) as IItemsItem[];
      this.closeDialog();
    } else if (this.step === 2) {
      const result = await (this.$refs.editItem as EditItem).validateFormData();
      if (result) {
        this.editItem(result);
        this.closeDialog();
      }
    } else if (this.step === 3) {
      if (this.selectedItem) {
        this.deleteItem(this.selectedItem.id as string);
        this.closeDialog();
      }
    } else if (this.step === 5) {
      const result = await (
        this.$refs.disposeDetails as DisposeDetails
      ).validateFormData();
      if (result) {
        this.SweetAlertService.success("successfully");
        this.closeDialog();
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/components/Customer/Dialog/Items/Items.scss";
</style>
